package com.szf.mail.service;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentLinkedQueue;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import com.szf.mail.bean.Mail;

@Component
public class MailManager {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private JavaMailSender mailSender;
	private ConcurrentLinkedQueue<Mail> mails;

	@Value("#{sinlog['mail.username']}")
	private String from;

	@PostConstruct
	public void init() {
		mails = new ConcurrentLinkedQueue<Mail>();
	}

	public void addMail(Mail mail) {
		mails.add(mail);
	}

	public void send() {
		logger.info("do send mail..");

		ConcurrentLinkedQueue<Mail> tmp = mails;
		mails = new ConcurrentLinkedQueue<Mail>();

		Map<String, List<Mail>> targetMap = new HashMap<String, List<Mail>>();

		for (Mail m : tmp) {
			List<Mail> list = targetMap.get(m.getTo());
			if (list == null) {
				list = new LinkedList<Mail>();
				targetMap.put(m.getTo(), list);
			}
			list.add(m);
		}

		for (Entry<String, List<Mail>> entry : targetMap.entrySet()) {
			try {
				MimeMessage mailMessage = mailSender.createMimeMessage();
				MimeMessageHelper helper = new MimeMessageHelper(mailMessage, true, "utf-8");

				Mail mergeMail = mergeMails(entry.getValue());
				helper.setFrom(mergeMail.getFrom());
				helper.setTo(mergeMail.getTo().split(";"));
				helper.setSubject(mergeMail.getSubject());
				helper.setText(mergeMail.getText(), true);

				mailSender.send(mailMessage);
			} catch (MessagingException e) {
				logger.error(e.getMessage(), e);
			}
		}
		logger.info("mail send over..");
	}

	private Mail mergeMails(List<Mail> list) {
		if (list == null || list.size() == 0) {
			return null;
		}
		Mail result = new Mail();
		Mail first = list.get(0);

		result.setTo(first.getTo());
		result.setFrom(from);
		result.setSubject("sinlog邮件");

		StringBuilder sb = new StringBuilder();
		int index = 1;
		int size = list.size();
		for (Mail m : list) {
			sb.append(m.getText());
			sb.append("<div style=\"text-align: center;color: gray;\">").append(index++).append("/").append(size).append("</div>");
			sb.append("<hr/>");
		}
		result.setText(sb.toString());

		return result;
	}

}
